use crate::cli::base64::Base64Format;
use crate::cli::base64::Base64Format::{Standard, UrlSafe};
use crate::utils::get_reader;
use base64::{
    engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
    Engine as _,
};
use std::io::Read;

pub fn process_encode(input: &str, format: Base64Format) -> anyhow::Result<String> {
    //如果input是-，则从标准输入读取，如果不是，则从文件读取
    // let input = if input == "-" {
    //     std::io::stdin()
    //         .lock()
    //         .bytes()
    //         .map(|b| b.unwrap())
    //         .collect::<Vec<u8>>()
    // } else {
    //     std::fs::read(input)?
    // };
    let mut input = get_reader(input)?;
    let mut buf = Vec::new();
    input.read_to_end(&mut buf)?;
    let data = match format {
        Standard => STANDARD.encode(buf),
        UrlSafe => URL_SAFE_NO_PAD.encode(buf),
    };
    // let data = data.trim().to_string();
    Ok(data)
}
pub fn process_decode(input: &str, format: Base64Format) -> anyhow::Result<Vec<u8>> {
    let mut input = get_reader(input)?;
    let mut buf = String::new();
    input.read_to_string(&mut buf)?;
    let buf = buf.trim();
    let data = match format {
        Standard => STANDARD.decode(buf)?,
        UrlSafe => URL_SAFE_NO_PAD.decode(buf)?,
    };
    Ok(data)
}
